//
//  DetailPhotoViewController.m
//  CarFace
//
//  Created by dlios on 15-3-28.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "DetailPhotoViewController.h"
#import "InfoPicCollectionViewCell.h"
#import "picWallpic.h"
@interface DetailPhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, retain)UICollectionViewFlowLayout *flowLayout;
//++
@property (nonatomic, assign)NSInteger set;
@property (nonatomic, retain)NSNumber *num;
@property (nonatomic, assign)NSInteger i;

@end

@implementation DetailPhotoViewController

-(void)handleData1
{
    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/pics-a2-pm2-v4.6.1-ss%@-sp0-cg%@-cl0-p%ld-s60-ft1.html",self.carID, self.pageStayID,self.set];
    
    NSLog(@"%@",str);
    //数组初始化
//    self.array = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        self.num = [[result valueForKey:@"result"]valueForKey:@"pagecount"];
        self.i = [self.num integerValue];
        
        NSMutableArray *array = [[result valueForKey: @"result"]valueForKey:@"piclist"];
        for (NSDictionary *dic in array) {
            picWallpic *info = [[picWallpic alloc]initWithDictionary:dic];
            [self.array addObject:info];
            [info release];
        }
        NSLog(@"1111%ld",self.order);
        //        [self.collectionView reloadData];
//        [self.collectionView setContentOffset:CGPointMake(_collectionView.frame.size.width * self.order, -64)];
        [self.collectionView reloadData];
        //        NSLog(@"1111%ld",self.order);
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@",error);
    }];
    
    
}



-(void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/pics-a2-pm2-v4.6.1-ss%@-sp0-cg%@-cl0-p1-s60-ft1.html",self.carID, self.pageStayID];
    NSLog(@"%@",str);
    //数组初始化
//    self.array = [NSMutableArray array];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        NSMutableArray *array = [[result valueForKey: @"result"]valueForKey:@"piclist"];
        [self.array removeAllObjects];
        for (NSDictionary *dic in array) {
            picWallpic *info = [[picWallpic alloc]initWithDictionary:dic];
            [self.array addObject:info];
            [info release];
        }
         NSLog(@"1111%ld",self.order);
//        [self.collectionView reloadData];
//        [self.collectionView setContentOffset:CGPointMake(_collectionView.frame.size.width * self.order, -64)];
        [self.collectionView reloadData];
//        NSLog(@"1111%ld",self.order);
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@",error);
    }];
    
    
}




- (void)dealloc
{

    [_collectionView release];
    [_array release];
    [_carID release];
    [_pageStayID release];
    [_flowLayout release];
    [super dealloc];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.array = [NSMutableArray array];
    self.set = 1;
    
    [self handleData1];
    NSLog(@"第%ld个图",self.order);
    //创建collectionView
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //设置滚动方向为水平方向
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height/2);
    self.flowLayout.minimumLineSpacing = 0;
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:self.flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = YES;
    [self.collectionView registerClass:[InfoPicCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.view addSubview:self.collectionView];
    [self.flowLayout release];
    [_collectionView release];
    
    
    
    //添加
//    [self.collectionView addHeaderWithTarget:self action:@selector(addheader:)];
//    [self.collectionView addFooterWithTarget:self action:@selector(footfresh:)];
//    [self.collectionView setHeaderRefreshingText:@"刷新网路..."];
//    [self.collectionView setFooterRefreshingText:@"网络加载中..."];
    
    
}


//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    NSLog(@"----content:%lf-----count:%ld------width:%lf",self.collectionView.contentOffset.x,self.array.count,self.collectionView.frame.size.width);
//    
//    if (self.collectionView.contentOffset.x  >= (self.array.count - 1) * self.collectionView.frame.size.width) {
//        NSLog(@"fdsaf");
////        [self footfresh:self.collectionView];
//    
//    }
//}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"----content:%lf-----count:%ld------width:%lf",self.collectionView.contentOffset.x,self.array.count,self.collectionView.frame.size.width);
    
    if (self.collectionView.contentOffset.x  >= (self.array.count - 1) * self.collectionView.frame.size.width) {
        NSLog(@"fdsaf");
        
        if (self.set < self.i) {
            _set = _set + 1;
            [self handleData1];
        }
    }

}

//- (void)addheader:(UICollectionView *)collectonView
//{
//    __unsafe_unretained typeof(self) vc= self;
//    [self.collectionView addHeaderWithCallback:^{
//        [self handleData];
//        
//        // 进入刷新状态就会回调这个Block
//        // 增加5条假数据
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [vc.collectionView reloadData];
//            // 结束刷新
//            [vc.collectionView headerEndRefreshing];
//        });
//
//        
//    } dateKey:@"collection"];
//    
//}


//- (void)footfresh:(UICollectionView *)collectionView
//{
//    __unsafe_unretained typeof(self) vc = self;
//    [self.collectionView addFooterWithCallback:^{
//        if (self.set < self.i) {
//            _set = _set + 1;
//            [self handleData1];
//        }
//        
//        [vc.collectionView footerEndRefreshing];
//        
//    }];
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [vc.collectionView reloadData];
//        // 结束刷新
//        [vc.collectionView footerEndRefreshing];
//    });
//}



/***********************collectionView的方法******************/


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   
    return self.array.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    InfoPicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    picWallpic *info = [self.array objectAtIndex:indexPath.row];
    NSString *str = [info valueForKey:@"smallpic"];
    NSArray *arr =  [str componentsSeparatedByString:@"s_"];
     cell.picAdress = [NSString stringWithFormat:@"%@w_%@", [arr firstObject], [arr lastObject]];
        return cell;
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
